#import "ContactContentViewController.h"
#import <AddressBook/AddressBook.h>
#import "IDominoAppDelegate.h"
@implementation ContactContentViewController
@synthesize displayList;
@synthesize currentPerson;

- (id)initWithStyle:(UITableViewStyle)style {
	if (self = [super initWithStyle:style]) {
		self.hidesBottomBarWhenPushed=YES;
        self.tableView.delegate = self;
		self.tableView.dataSource = self; 
		self.tableView.rowHeight=50;
	}
    return self;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [displayList count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"ContactContentCell";
    // Set up the cell...
	if(indexPath.row == 0  ){
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddToIPhoneTableViewCell"];
		if(cell==nil){
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AddToIPhoneTableViewCell"] autorelease];
		}

		cell.textLabel.font=[UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
		cell.textLabel.textColor = [UIColor blueColor];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		cell.textLabel.text=[displayList objectAtIndex:indexPath.row];
		return cell;
	}
	else if(indexPath.row==1){
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NameTableViewCell"];
		if(cell==nil){
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NameTableViewCell"] autorelease];
		}
		
		cell.textLabel.font=[UIFont boldSystemFontOfSize:[UIFont buttonFontSize]];
		cell.textLabel.text=[displayList objectAtIndex:indexPath.row];
		return cell;
	}
	else{
		UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
		if (cell == nil) {
			cell = [[[UITableViewCell alloc]  initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:CellIdentifier] autorelease];
		}
		cell.accessoryType = UITableViewCellAccessoryNone;
		NSString* attribute =[displayList objectAtIndex:indexPath.row];
		
		if(([attribute rangeOfString:@":"].location)!=NSNotFound){
			int location=[attribute rangeOfString:@":"].location+1;
			cell.textLabel.text=[attribute substringToIndex:location];
			cell.textLabel.textColor=[UIColor lightGrayColor];
			cell.textLabel.font=[UIFont systemFontOfSize:14];
			cell.detailTextLabel.text=[attribute substringFromIndex:location];
			cell.detailTextLabel.textColor=[UIColor blackColor];
			cell.detailTextLabel.font=[UIFont systemFontOfSize:18];
		}
		return cell;
	}

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:NO];
	if(indexPath.row!=0){
		NSString* attribute=[displayList objectAtIndex:indexPath.row];
		if([attribute hasPrefix:@"Mobile: "]){
			// open a alert with an OK and cancel button
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[attribute substringFromIndex:8]
														   delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Dial", nil];
			[alert show];
			[alert release];
			
		}else if([attribute hasPrefix:@"Work Phone: "]){
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[attribute substringFromIndex:12]
														   delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Dial", nil];
			[alert show];
			[alert release];
		}
		else if([attribute hasPrefix:@"Email: "]){
			NSString* info=[attribute substringFromIndex:7];
			IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
			[appDelegate.contactNavigationController popViewControllerAnimated:NO];
			[appDelegate sendMailTo:info];
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:info]];//is it right?
		}
		[[UIPasteboard generalPasteboard] setValue:[displayList objectAtIndex:indexPath.row] forPasteboardType:@"kUTTypeText"];
		
	}
	else
		[self importPersonToAddressBook];
	
}



- (void)setUpDisplayList:(Person *) person{
	if(currentPerson!=nil)
		[currentPerson release];
	currentPerson=[person retain];
	NSMutableArray* newArray=[[NSMutableArray alloc] init] ;
	[newArray addObject:NSLocalizedString(@"AddToIPhone", @"Add To IPhone Contact List")];
	[newArray addObjectsFromArray:[person detailInformationArray]];
	displayList=newArray;
	[self.tableView reloadData];

}

- (void)importPersonToAddressBook{
	ABAddressBookRef addressBook=ABAddressBookCreate();	
	ABRecordRef aRecord = ABPersonCreate();	
	CFErrorRef  anError = NULL;
	
	ABRecordSetValue(aRecord, kABPersonPrefixProperty,
					currentPerson.prefix, &anError);	
	ABRecordSetValue(aRecord, kABPersonFirstNameProperty,
					currentPerson.firstName, &anError);	
	ABRecordSetValue(aRecord, kABPersonMiddleNameProperty,
					 currentPerson.middleName, &anError);
	ABRecordSetValue(aRecord, kABPersonLastNameProperty,
					 currentPerson.lastName, &anError);
	ABRecordSetValue(aRecord, kABPersonSuffixProperty,
					 currentPerson.suffix, &anError);
	ABRecordSetValue(aRecord, kABPersonJobTitleProperty,
					 currentPerson.jobTitle, &anError);	
	ABRecordSetValue(aRecord, kABPersonDepartmentProperty,
					 currentPerson.department, &anError);
	ABRecordSetValue(aRecord, kABPersonOrganizationProperty,
					 currentPerson.company, &anError);

	ABMultiValueIdentifier identifier;
	ABMutableMultiValueRef multi=ABMultiValueCreateMutable(kABMultiStringPropertyType);
	ABMultiValueAddValueAndLabel(multi,currentPerson.email , CFSTR("work"),&identifier);
	ABRecordSetValue(aRecord, kABPersonEmailProperty, multi, &anError);
	CFRelease(multi);
	/*multi=ABMultiValueCreateMutable(kABMultiDateTimePropertyType);
	ABMultiValueAddValueAndLabel(multi, CFDateFormatterCreateDateFromString(NULL,
								 NULL,CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), currentPerson.birthday),NULL), 
								 CFSTR("birthday"),&identifier);
	ABRecordSetValue(aRecord, kABPersonBirthdayProperty, multi, &anError);*/
	

	ABMutableMultiValueRef address = ABMultiValueCreateMutable(kABDictionaryPropertyType);
    CFStringRef keys[5];
    CFStringRef values[5];
    keys[0]      = kABPersonAddressStreetKey;
    keys[1]      = kABPersonAddressCityKey;
    keys[2]      = kABPersonAddressStateKey;
    keys[3]      = kABPersonAddressZIPKey;
    keys[4]      = kABPersonAddressCountryKey;
    values[0]    = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), currentPerson.street);
    values[1]    = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), currentPerson.city);
    values[2]    = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), currentPerson.state);
    values[3]    = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), currentPerson.zip);
    values[4]    = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@"), currentPerson.country);
    CFDictionaryRef aDict = CFDictionaryCreate(NULL, (void *)keys, (void *)values, 5, &kCFCopyStringDictionaryKeyCallBacks,
											  &kCFTypeDictionaryValueCallBacks);

    ABMultiValueAddValueAndLabel(address, aDict, kABHomeLabel, &identifier);
	ABRecordSetValue(aRecord, kABPersonAddressProperty, address, &anError);
    CFRelease(aDict);
    CFRelease(address);

	
	 multi =ABMultiValueCreateMutable(kABMultiStringPropertyType);
	bool didAdd = ABMultiValueAddValueAndLabel(multi, currentPerson.mobile, kABPersonPhoneMobileLabel, NULL)
							&& ABMultiValueAddValueAndLabel(multi, currentPerson.workPhone,kABPersonPhoneMainLabel, NULL) 
							&& ABMultiValueAddValueAndLabel(multi,  currentPerson.workFax,kABPersonPhoneWorkFAXLabel, NULL)
							&& ABMultiValueAddValueAndLabel(multi,  currentPerson.workPager,kABPersonPhonePagerLabel, NULL)
							&& ABMultiValueAddValueAndLabel(multi,  currentPerson.homeFax,kABPersonPhoneHomeFAXLabel, NULL);
	if (didAdd != YES) {NSLog(@"error contact content");}	
	ABRecordSetValue(aRecord, kABPersonPhoneProperty, multi, &anError);
	CFRelease(multi);
	

	multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    didAdd = ABMultiValueAddValueAndLabel(multi, currentPerson.street, kABPersonHomePageLabel, NULL);
	if (didAdd != YES) {NSLog(@"error contact content");}	
	ABRecordSetValue(aRecord, kABPersonURLProperty, multi, &anError);
	CFRelease(multi);
	
	if (anError != NULL) 
	{ 
		NSLog(@"contactcontent error");
	}
	
	
    ABNewPersonViewController * addViewController=[[ABNewPersonViewController  alloc] init];	
	addViewController.newPersonViewDelegate =self;
	addViewController.addressBook=addressBook;
	addViewController.displayedPerson=aRecord;
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	[appDelegate.contactNavigationController pushViewController:addViewController	animated:YES];
	/*ABAddressBookAddRecord(addressBook, aRecord, &anError);
	if (ABAddressBookHasUnsavedChanges(addressBook)) {
		ABAddressBookSave(addressBook, &anError);
	}*/
	[addViewController release];
	CFRelease(addressBook);
}

- (void)newPersonViewController:(ABNewPersonViewController *)newPersonViewController didCompleteWithNewPerson:(ABRecordRef)person
{
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	[appDelegate.contactNavigationController popViewControllerAnimated:YES];
}
- (void)dealloc {
    [super dealloc];
}


- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(buttonIndex==1){
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",actionSheet.message]]];
	}
}


@end

